<template>
    <el-dialog :title="selectList.length===0 ? `复制任务${taskName}` : `创建新群发任务`" :visible.sync="dialogTableVisible" :show-close="false" :center="true" top="4vh" :before-close="beforeClose">
        <div class="dialogVue">
            <div class="innerVue" ref="msgRef">
                
                <div class="inpVue">
                    <div class="label">请为复制的新任务创建名称，方便您后续跟踪管理</div>
                    <el-input v-model="newTaskName" placeholder="请输入任务名" style="width: 250px; margin-top: 10px;" :maxlength="12"></el-input>
                </div>

                <div class="inpVue">
                    <div class="label">请选择发送方的微信</div>
                    <el-select v-model="currentWeChat.currentUserWechatName" placeholder="选择微信AI客服" style="width: 250px; margin-top: 10px;" @change="handleChange">
                        <el-option v-for="item in weChatList" :key="item.id" :label="item.wechatName" :value="item"></el-option>
                    </el-select>
                </div>
  
                <!-- 选择日期 -->
                <div class="dataVue margin10">
                    <div class="label">发布时间</div>
                    <el-radio v-model="dateType" :label="1" text-color="#0147fd" fill="#0147fd">特定日期</el-radio>
                    <el-radio v-model="dateType" :label="2">每天</el-radio>
                    <el-radio v-model="dateType" :label="3">周期循环</el-radio>
                    <el-radio v-model="dateType" :label="4">立即发送</el-radio>
                    <!-- 特定日期 -->
                    <template v-if="dateType===1">
                        <div class="flex align_center margin10">
                            <span>选择发布日期时间：</span>
                            <el-date-picker v-model="datetime" type="datetime" placeholder="选择发送日期时间" value-format="yyyy-MM-dd HH:mm" format="yyyy-MM-dd HH:mm" :picker-options="disableOptions" @change="dateChange" :editable="false"></el-date-picker>
                        </div>
                    </template>
                    <!-- 每天 -->
                    <template v-if="dateType===2">
                        <div class="flex align_center margin10">
                            <span>选择发布时间：</span>
                            <el-time-picker v-model="everyTime" value-format="HH:mm" format="HH:mm" :picker-options="{ selectableRange: '00:00:00 - 23:59:00' }" placeholder="选择发布时间"  @change="everyTimeChange"></el-time-picker>
                        </div>
                    </template>
                    <!-- 周期循环 -->
                    <template v-if="dateType===3">
                        <div class="flex align_center margin10">
                            <span>选择发布周期：</span>
                            <div class="week" :class="{active: selectDays.includes(o)}" v-for="(o, i) in days" :key="i" @click="selectWeekFun(o)">{{ o }}</div>
                        </div>
                        <div class="flex align_center margin10">
                            <span>选择发布时间：</span>
                            <el-time-picker v-model="time" value-format="HH:mm" format="HH:mm" :picker-options="{ selectableRange: '00:00:00 - 23:59:00' }" placeholder="选择发布时间" @change="timeChange"></el-time-picker>
                        </div>
                    </template>
                    <div class="tip">请注意，您设置的群发时间是任务的开始时间，消息将按队列依次发送，这意味着用户接收消息的时间可能会有所不同，您当前任务：群发100人，整个任务大约需要10分钟完成，预计2024年7月11日10:51开始发送</div>
                </div>  

                <div class="messageVue margin10">
                    <div class="label">发布内容</div>
                    <div class="messageItem relative" v-for="(item, index) in msgArray" :key="index" :class="{messageActive: index==msgIndex}">
                        <el-radio v-model="msgArray[index].messageType" :label="1">自定义文本内容</el-radio>
                        <el-radio v-model="msgArray[index].messageType" :label="2">自定义图片内容</el-radio>
                        <el-radio v-model="msgArray[index].messageType" :label="3">自定义视频内容</el-radio>
                        <span class="el-icon-close absolute" style="top: 10px; right: 10px; font-size: 18px; color: #AAA; cursor: pointer;" v-if="index!=0" @click="removeMsgArray(index)"></span>
                        <template v-if="msgArray[index].messageType===1">
                            <div class="flex_between align_center margin10">
                                <div class="flex align_center">
                                    <span style=" color: #666; font-size: 12px; padding-right: 10px;">使用AI生成内容</span>
                                    <el-switch v-model="msgArray[index].isAi" active-color="#0147fd" inactive-color="#999"></el-switch>
                                </div>
                                <div class="flex align_center" v-if="msgArray[index].isAi && (dateType===2 || dateType===3)">
                                    <span style=" color: #666; font-size: 12px; padding-right: 10px;">每次任务都生成差异化的内容</span>
                                    <el-switch v-model="msgArray[index].isDifferent" active-color="#0147fd" inactive-color="#999"></el-switch>
                                </div>
                            </div>
                            <template v-if="msgArray[index].isAi && !msgArray[index].isDifferent">
                                <textarea v-model="msgArray[index].describetion" placeholder="请大概描述你需要AI生成的内容需求"></textarea>
                                <div class="flex align_center" style="padding: 10px 0;">
                                    <span style="color: #AAA; font-size: 12px;">AI生成内容预览</span>
                                    <div class="btn" v-if="msgArray[index].loading">
                                        <span class="el-icon-loading" style="color: #fff;"></span>
                                    </div>
                                    <div class="btn" @click="getAiMsg(index)" v-else>生成</div>
                                </div>
                                <textarea v-model="msgArray[index].aiMsg" style="margin-top: 0"></textarea>
                            </template>
                            <textarea v-model="msgArray[index].msg" placeholder="请输入自定义文本内容" v-if="!msgArray[index].isAi"></textarea>
                            <textarea v-model="msgArray[index].msg" placeholder="请输入提示词，AI根据提示词生成内容" v-if="msgArray[index].isAi && msgArray[index].isDifferent"></textarea>
                        </template>
                        <template v-if="msgArray[index].messageType===2">
                            <div class="flex">
                                <div class="uploadVue flex_center align_center relative">
                                    <span class="el-icon-loading" v-if="msgArray[index].loading"></span>
                                    <template v-else>
                                        <span class="el-icon-plus" style="color: #AAA;"></span>
                                        <span style="color: #AAA; padding-left: 5px;">选择图片</span>
                                        <input ref="clearRef" class="fileBtn" type="file" id="fileupload" accept=".jpg, .png, .jpeg" @change="imgChange($event, index)"/>
                                    </template>
                                </div>
                                <div class="show flex align_center" v-if="msgArray[index].imgName">
                                    <span>{{ msgArray[index].imgName.split('/')[msgArray[index].imgName.split('/').length-1] }}</span>
                                    <span class="el-icon-close" style="padding-left: 5px; font-size: 16px; cursor: pointer;" @click="msgArray[index].imgName=''"></span>
                                </div>
                            </div>
                        </template>
                        <template v-if="msgArray[index].messageType===3">
                            <div class="flex">
                                <div class="uploadVue flex_center align_center relative">
                                    <span class="el-icon-loading" v-if="msgArray[index].loading"></span>
                                    <template v-else>
                                        <span class="el-icon-plus" style="color: #AAA;"></span>
                                        <span style="color: #AAA; padding-left: 5px;">选择视频</span>
                                        <input ref="clearRef" class="fileBtn" type="file" id="fileupload" accept=".mp4" @change="videoChange($event, index)"/>
                                    </template>
                                </div>
                                <div class="show flex align_center" v-if="msgArray[index].videoName">
                                    <span>{{ msgArray[index].videoName.split('/')[msgArray[index].videoName.split('/').length-1] }}</span>
                                    <span class="el-icon-close" style="padding-left: 5px; font-size: 16px; cursor: pointer;" @click="msgArray[index].videoName=''"></span>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="messageAdd" @click="addMessage" v-if="msgArray.length<5">再加一条</div>
                </div>
            </div>
            <div class="btnVue flex_between">
                <div></div>
                <div class="flex">
                    <div class="btn" @click="beforeClose">取消</div>
                    <div class="btn" @click="submitFun">
                        <span class="el-icon-loading" v-if="loading"></span>
                        <span v-else>发送</span>
                    </div>
                </div> 
            </div>
        </div>
    </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { toast, formatTime } from '@/common/tools';
import { post } from '@/common/request';
export default {
    props: {
        dialogTableVisible: {
            type: Boolean,
            default: false
        },
        taskName: {
            type: String,
            default: ""
        },
        selectList: {
            type: Array,
            default: ()=>[]
        },
    },
    data(){
        return {
            dateType: 1,
            datetime: "",
            disableOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
            days: ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
            selectDays: [],
            time: "",
            everyTime: "",
            msg: "",
            msgArray: [{
                messageType: 1,
                isAi: false,
                msg: "",
                describetion: "",
                aiMsg: "",
                imgName: "",
                videoName: "",
                isDifferent: false,
                loading: false,
            }],
            isLoading: false,
            loading: false,
            msgIndex: null,
            list: [],
            newTaskName: "",
            applicationId: "",
        }
    },
    computed: {
        ...mapState({
            currentWeChat: state=> state.currentWeChat,
            weChatList: state=> state.weChatList,
        })
    },
    methods: {
        beforeClose(){
            this.$store.state.selectList = []
            this.msgArray = [{
                messageType: 1,
                isAi: false,
                msg: "",
                describetion: "",
                aiMsg: "",
                imgName: "",
                videoName: "",
                isDifferent: false,
                loading: false,
            }]
            this.time = ""
            this.everyTime = ""
            this.datetime = ""
            this.newTaskName = ""
            this.$emit("beforeClose")
        },

        // 获取发送对象列表
        getList(id, contentList, type, timing){
            console.log("kkkkkkkkkkk", id, contentList, type, timing)
            if(type) this.dateType = type
            if(timing) {
                if(type===1) this.datetime = timing
                else if(type===2) this.everyTime = timing
                else if(type===3) this.time = timing
            }
            if(contentList && contentList.length>0) {
                this.msgArray = []
                for(let i=0; i<contentList.length; i++) {
                    console.log(i)
                    let obj = {
                        messageType: contentList[i].type,
                        isAi: false,
                        msg: contentList[i].content,
                        describetion: "",
                        aiMsg: contentList[i].aiContent,
                        imgName: contentList[i].content,
                        videoName: contentList[i].content,
                        isDifferent: false,
                        loading: false,
                    }
                    console.log(obj)
                    this.msgArray.push(obj)
                }
            }
            this.$post("/front/timing/friendList", {
                id: id,
                pageNum: 1,
                pageSize: 10000
            }).then(res=>{
                if(res.data.code===0) {
                    this.list = res.data.obj.list
                    console.log("pppp", this.list)
                }
            })
        },

        handleChange(e){
            let obj = this.currentWeChat
            obj.currentWeChatId = e.id
            obj.currentUserWechatName = e.wechatName
            this.$store.state.currentWeChat = obj
            window.sessionStorage.setItem("currentWeChatId", e.id)
            window.sessionStorage.setItem("currentUserWechatName", e.wechatName)
            window.sessionStorage.setItem("currentOnLineStatus", e.status)
            this.$store.state.hasUnreadMsg = false
            this.$store.state.currentChat = {}
            this.$store.state.history = []
            this.$emit("getList")
        },


        imgChange(e, index){
            console.log(e, index)
            var file = e.target.files[0];
            var formData = new FormData()
            formData.append("file", file)
            this.msgArray[index].loading = true
            this.$forceUpdate()
            post("/front/search/uploadImage", formData).then(res=>{
                if(this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                this.msgArray[index].loading = false
                this.$forceUpdate()
                if(res.data.code===0) this.msgArray[index].imgName = res.data.obj 
            })
        },

        videoChange(e, index){
            console.log(e, index)
            var file = e.target.files[0];
            var formData = new FormData()
            formData.append("file", file)
            this.msgArray[index].loading = true
            this.$forceUpdate()
            post("/front/search/uploadVideo", formData).then(res=>{
                if(this.$refs.clearRef.value) this.$refs.clearRef.value = ''; // 清空file文件
                this.msgArray[index].loading = false
                this.$forceUpdate()
                if(res.data.code===0) this.msgArray[index].videoName = res.data.obj
            })
        },

        // 选择周期循环
        selectWeekFun(o){
            if(this.selectDays.includes(o)) {
                this.selectDays = this.selectDays.filter(item=>{
                    return item != o
                })
            }else{
                this.selectDays.push(o)
            }
        },

        // 选择日期时间
        dateChange(e){
            let timestamp = new Date(e).getTime()
            this.datetime = formatTime(timestamp, "YMDHMS")
        },

        // 选择时间
        timeChange(e){
            console.log(e)
            // let timestamp = new Date(e).getTime()
            this.time = e
        },

        everyTimeChange(e){
            this.everyTime = e
        },

        removeMsgArray(index){
            this.msgArray = this.msgArray.slice(0, index).concat(this.msgArray.slice(index + 1));
        },

        addMessage(){
            this.msgArray.push({
                messageType: 1,
                isAi: false,
                msg: "",
                describetion: "",
                aiMsg: "",
                imgName: "",
                videoName: "",
                loading: false,
                isDifferent: false
            })
            // 滑动到聊天最底部
            this.$nextTick(()=>{
                let dom = this.$refs.msgRef
                dom.scrollTo({ top: dom.scrollHeight, behavior: 'smooth' });
            })
        },

        getAiMsg(index){
            if(!this.msgArray[index].describetion) return toast(1, "请大概描述你需要生成的内容需求")
            if(this.msgArray[index].loading) return
            this.msgArray[index].loading = true
            this.weChatList.forEach(o=>{
                if(o.id==this.currentWeChat.currentWeChatId) {
                    console.log("this.applicationId = o.applicationId")
                    this.applicationId = o.applicationId
                }
            })
            this.$post("/front/userWechat/returnModelAnswer", {
                applicationId: this.applicationId,
                message: this.msgArray[index].describetion
            }).then(res=>{
                if(res.data.code===0) {
                    console.log(res)
                    this.msgArray[index].loading = false
                    this.msgArray[index].aiMsg = res.data.obj
                }else {
                    this.msgArray[index].loading = false
                    toast(1, res.data.msg)
                }
            })
        },

        // 创建定时消息
        submitFun(){
            if(!this.newTaskName) return toast(1, "请输入任务名")
            if(this.dateType===1 && !this.datetime) return toast(1, "请选择发布日期")
            if(this.dateType===1) {
                let timestamp = new Date(this.datetime).getTime()/1000
                let now = Math.ceil(new Date().getTime()/1000)
                if(timestamp - now <= 0) return toast(1, "选择的发布时间小于当前时间，请重新选择")
            }
            if(this.dateType===2 && !this.everyTime) return toast(1, "请选择发布时间")
            if(this.dateType===3 && this.selectDays.length===0) return toast(1, "请选择发布周期")
            if(this.dateType===3 && !this.time) return toast(1, "请选择发布时间")
            for(let i=0; i<this.msgArray.length; i++) {
                if(this.msgArray[i].messageType===1 && !this.msgArray[i].isAi && !this.msgArray[i].msg) {
                    toast(1, "请输入自定义文本内容")
                    this.msgIndex = i
                    this.clearError()
                    return 
                }
                if(this.msgArray[i].messageType===1 && this.msgArray[i].isAi && this.msgArray[i].isDifferent && !this.msgArray[i].msg) {
                    toast(1, "请输入提示词，AI根据提示词生成内容")
                    this.msgIndex = i
                    this.clearError()
                    return 
                }
                if(this.msgArray[i].messageType===2 && !this.msgArray[i].imgName) {
                        this.msgIndex = i
                    this.clearError()
                    toast(1, "请上传图片文件")
                    return 
                }
                if(this.msgArray[i].messageType===2 && !this.msgArray[i].imgName) {
                    this.msgIndex = i
                    this.clearError()
                    toast(1, "请上传图片文件")
                    return 
                }
                if(this.msgArray[i].messageType===3 && !this.msgArray[i].videoName) {
                    this.msgIndex = i
                    this.clearError()
                    toast(1, "请上传视频文件")
                    return 
                }
            }

            let array = []
            let list = this.selectList.length===0 ? this.list : this.selectList
            for(let i=0; i<list.length; i++){
                if(this.selectList.length===0) array.push(list[i].id)
                else array.push(list[i].receiverId)
            }    

            console.log(array,"1111111111111")

            // 处理时间和循环类型
            console.log(this.dateType)
            if(this.dateType===1) {
                var timing = this.datetime
                console.log(this.datetime,"this.datetime")
            } 
            if(this.dateType===2) {
                console.log(this.everyTime,"this.everyTime")
                var timing = this.everyTime
            }
            if(this.dateType===3) {
                console.log(this.time,"this.time")
                var timing = this.time
                var cycle = this.selectDays.join(",")
            }

            // 处理消息
            let contentList = []
            for(let i=0; i<this.msgArray.length; i++) {
                let content = ""
                let aiContent = ""
                if(this.msgArray[i].messageType===1) {
                    if(this.msgArray[i].isAi) {
                        if(this.msgArray[i].isDifferent) {
                            content = this.msgArray[i].msg
                        }else{
                            aiContent = this.msgArray[i].aiMsg
                        }
                    }else{
                        content = this.msgArray[i].msg
                    } 
                }
                if(this.msgArray[i].messageType===2) content = this.msgArray[i].imgName
                if(this.msgArray[i].messageType===3) content = this.msgArray[i].videoName
                let obj = {
                    type: this.msgArray[i].messageType,
                    aiAutoGenerate: this.msgArray[i].isAi,
                    aiAutoEveryday: this.msgArray[i].isDifferent,
                    content: content,
                    aiContent: aiContent
                }
                contentList.push(obj)
            }
            this.loading = true
            post("/front/timing/createTimingTask", {
                wechatId: this.currentWeChat.currentWeChatId,
                wechatName: this.currentWeChat.currentUserWechatName,
                receiverIds: array,
                name: this.newTaskName,
                type: this.dateType,
                cycle: cycle,
                timing: timing,
                contentList: contentList
            }).then(res=>{
                console.log(res)
                this.loading = false
                if(res.data.code===0) {
                    toast(0, "创建成功")
                    this.beforeClose()
                    this.$emit("callback")
                }else{
                    toast(1, res.data.msg)
                }
            })
        },
    }
}
</script>

<style lang="less" scoped>
:deep(.el-dialog) {
    width: 800px;
    height: 90vh;
}
:deep(.el-dialog__header) {
    padding: 20px 0 5px;
}
:deep(.el-dialog__body) {
    padding: 0;
}
.dialogVue {
    width: 100%;
    height: 90vh;
    padding: 0 15px;
    .innerVue {
        width: 100%;
        height: calc(90vh - 99px);
        overflow-y: scroll;
        .inpVue {
            width: 100%;
            margin-top: 10px;
            .label {
                font-size: 12px;
                line-height: 1.4;
                span {
                    color: #0147fd;
                }
            }
        }
        .dataVue {
            width: 100%;
            border: 1px solid #DCDFE6;
            border-radius: 5px;
            padding: 10px;
            .label {
                color: #111;
                font-weight: 600;
                font-size: 12px;
                padding-bottom: 15px;
            }            
            .week {
                width: 80px;
                height: 40px;
                border: #DCDFE6  1px solid;
                margin-right: 10px;
                border-radius: 4px;
                line-height: 40px;
                text-align: center;
                color: #999;
                cursor: pointer;
            }

            .active {
                background: #0147fd;
                color: #fff;
            }

            .tip {
                color: #AAA;
                font-size: 12px;
                padding-top: 10px;
                line-height: 1.4;
            }
        }
    }
    .innerVue::-webkit-scrollbar {
        width: 0;
        height: 0;
    }

    .messageVue {
        width: 100%;
        border: 1px solid #f5f5f5;
        border-radius: 5px;
        padding: 10px;
        .label {
            color: #111;
            font-weight: 600;
            font-size: 12px;
        }
        .messageAdd {
            width: 100%;
            height: 40px;
            text-align: center;
            line-height: 40px;
            background: #f5f5f5;
            margin-top: 10px;
            color: #AAA;
            cursor: pointer;
            font-size: 12px;
        }
        .messageItem {
            width: 100%;
            border: 1px solid #f5f5f5;
            border-radius: 5px;
            padding: 10px;
            margin-top: 10px;
            .label {
                color: #111;
                font-weight: 600;
                font-size: 12px;
                padding-bottom: 15px;
            }
            .btn {
                width: 60px;
                height: 32px;
                background: #0147fd;
                border-radius: 4px;
                margin-left: 6px;
                line-height: 32px;
                text-align: center;
                color: #fff;
                font-size: 12px;
                cursor: pointer;
            }
            .uploadVue {
                width: 120px;
                height: 38px;
                background: #f5f5f5;
                border-radius: 5px;
                margin-top: 10px;
                cursor: pointer;
                .fileBtn {
                    width: 100%;
                    height: 100%;
                    position: absolute;
                    left: 0;
                    top: 0;
                    opacity: 0;
                    cursor: pointer;
                    z-index: 98;
                    border: none;
                    outline: none;
                }
            }
            .show {
                padding: 0 10px;
                background: #f5f5f5;
                border-radius: 5px;
                margin-top: 10px;
                margin-left: 10px;
                span {
                    color: #AAA;
                }
            }
            textarea {
                width: 100%;
                height: 60px;
                border: #f5f5f5 1px solid;
                display: block;
                box-sizing: border-box;
                resize: none;
                border-radius: 4px;
                margin-top: 10px;
                line-height: 1.4;
                font-family: PingFangSC, PingFang SC;
                padding: 10px;
                font-size: 13px;
            }        
            textarea::-webkit-scrollbar {
                width: 0;
                height: 0;
            }        
            ::-webkit-input-placeholder { /* WebKit browsers */
                color: #AAA;
                font-size: 13px;
                font-family: PingFangSC, PingFang SC;
            }
            :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
                color: #AAA;
                font-size: 13px;
                font-family: PingFangSC, PingFang SC;
            }
            ::-moz-placeholder { /* Mozilla Firefox 19+ */
                color: #AAA;
                font-size: 13px;
                font-family: PingFangSC, PingFang SC;
            }
            :-ms-input-placeholder { /* Internet Explorer 10+ */
                color: #AAA;
                font-size: 13px;
                font-family: PingFangSC, PingFang SC;
            }
        }
        .messageActive {
            border: 1px solid #f4ea2a;
        }          
    }

    .btnVue {
        width: 100%;
        height: 50px;
        .btn {
            width: 100px;
            height: 40px;
            text-align: center;
            line-height: 40px;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 10px;
            span {
                color: #fff;
            }
        }
        .btn:nth-child(1) {
            background: #f5f5f5;
        }
        .btn:nth-child(2) {
            background: #0147fd;
            color: #fff;
        }
    }
}
</style>